from app import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
import pytz  # 新增: 用于处理时区

# 设置上海时区
SHANGHAI_TZ = pytz.timezone('Asia/Shanghai')

class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(SHANGHAI_TZ))
    updated_at = db.Column(db.DateTime, default=lambda: datetime.now(SHANGHAI_TZ),
                          onupdate=lambda: datetime.now(SHANGHAI_TZ))

    # 关联订单
    orders = db.relationship('Order', backref='user', lazy=True)

    def set_password(self, password):
        """设置密码，将明文密码转换为哈希存储"""
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):  # 新增: 密码验证方法
        """验证密码是否正确
        Args:
            password: 明文密码
        Returns:
            bool: 密码是否正确
        """
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return f'<User {self.username}>'
